<template>
  <zh-form
    :span="6"
    ref="rolePageFrom"
    :labelCol="labelCol"
    enctype="multipart/form-data"
    :wrapperCol="wrapperCol"
    :model="form"
    :rules="rules"
  >
    <div style="width: 100%;">
      <div class="shp-upload">
        <a-upload
          title="文物保护范围"
          :before-upload="beforeUpload"
          :customRequest="customRequest1"
          :show-file-list="false"
          @change="handleRange"
          :file-list="fileList1"
        >
          <ep-button style="margin-left: -10px">文物保护范围（上传）</ep-button>
        </a-upload>
        <a-upload
          title="建设控制地带范围（上传）"
          :before-upload="beforeUpload"
          :customRequest="customRequest2"
          :show-file-list="false"
          @change="handleControl"
          :file-list="fileList2"
        >
          <ep-button style="margin-left: 15px"
            >建设控制地带范围（上传）</ep-button
          >
        </a-upload>
        <span style="color: #fff">（请上传国家2000坐标，shp文件）</span>
      </div>
      <div class="map-box">
        <div id="map"></div>
        <!--<div class="scale">-->
        <!--  <p @click="checkAreaEnlarge">-->
        <!--    <span>+</span>-->
        <!--  </p>-->
        <!--  <p @click="checkAreaNarrow">-->
        <!--    <span>-</span>-->
        <!--  </p>-->
        <!--</div>-->
        <div class="eidt">
          <ep-button style="margin-left: 8px" @click="startEdit"
            >开始编辑</ep-button
          >
          <ep-button style="margin-left: 8px" @click="endEdit"
            >结束编辑</ep-button
          >
        </div>
      </div>
    </div>
  </zh-form>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import * as L from "leaflet";
require('leaflet/dist/leaflet.css')
import { readSHP } from "@/services/system/whdngxlApi";
import { fileShowUrl,fileUploadUrl } from "@/services/system/api";
import {httpAction} from "@/services/http";

export default {
  props: {
    data: {
      type: Object,
      default: () => {}
    },
    b0119Data: {
      required: false,
      type: Array,
      default: ()=> []
    },
    fileList1: {
      required: false,
      type: Array,
      default: ()=> []
    },
    b0120Data: {
      required: false,
      type: Array,
      default: ()=> []
    },
    fileList2: {
      required: false,
      type: Array,
      default: ()=> []
    }
  },
  data() {
    return {
      dictData: {},
      editFlag: true,
      isPolygonEdit: false, // 判断古文物保护范围和建设控制地带范围是否在编辑。 如果是正在编辑，点击保存的时候，提示先结束编辑。目的是拿到编辑后的结果
      form: {
        b0101: null,
        b0107: "",
        b0108: "",
        b0117: "",
        b0118: "",
        b0104: "",
        b0105: "",
        b0106: "",
        b0115: "",
        b0114: "",
        b0113: "",
        b0116: "",
        b0109: "",
        b0111: "",
        b0112: "",
        address: "",
        longitude: "", // 国家2000坐标
        latitude: "",
        gpsLongitude: "", // 高德地图坐标
        gpsLatitude: "",
      },
      zoomSize: 12,
      marker: "",
      areaMap: null,
      url: readSHP,
      areaForm: {
        range: [],
        control: [],
      },
      rangePolygon: null,
      controlPolygon: null,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      rules: {
        b0101: [{ required: true, message: "请输入文物编号" }],
      },
    };
  },
  created() {
    this.init();
  },
  mounted() {
    this.initMap();
    // console.log(this.b0119Data)
    if(this.b0119Data.length > 0){
      this.b0119Data.forEach((item) => {
        this.rangeDraw(eval('[' +  item.the_geom + ']'), '#9640ff');
      })
    }
    if(this.b0120Data.length > 0){
      this.b0120Data.forEach((item) => {
        this.rangeDraw(eval('[' +  item.the_geom + ']'), '#ff8940');
      })
    }
    if(this.fileList1.length > 0){
      this.fileList1[0].datas.forEach((item) => {
        this.rangeDraw(eval('[' +  item.the_geom + ']'), '#9640ff');
      })
    }
    if(this.fileList2.length > 0){
      this.fileList2[0].datas.forEach((item) => {
        this.rangeDraw(eval('[' +  item.the_geom + ']'), '#ff8940');
      })
    }
  },
  beforeDestroy() {
    // 销毁地图
    if (this.areaMap) {
      this.areaMap.destroy();
    }
  },
  methods: {
    init() {
      this.form.gpsLongitude = this.data.b0126
      this.form.gpsLatitude = this.data.b0127
    },
    initMap() {
      this.map = L.map('map', {
        layers: [
          L.tileLayer(
              "http://t7.tianditu.gov.cn/img_w/wmts?" +
              "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
              "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=a54f58695e1cd9bce8dd12afdc249428"  //tk: 问前端主管要
          ),
          L.tileLayer(
              "http://t0.tianditu.gov.cn/cva_w/wmts?" +
              "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
              "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=a54f58695e1cd9bce8dd12afdc249428"  //tk: 问前端主管要
          ),
          // L.geoJSON(wzJson, {
          //   style: style,
          // }),
        ],
        center: [
          this.form.gpsLatitude || 27.993849,
          this.form.gpsLongitude || 120.699279,
        ],
        zoom: 18,
        zoomControl: true,
        needPolygon: true,
        attributionControl: false
      });
    },
    // 保护范围-地图
    initAreaMap() {
      AMapLoader.load({
        key: "e38ea4dfc12f0fd7864f078c6ce7b48d", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.Marker",
          "AMap.Pixel",
          "AMap.DistrictSearch",
          "AMap.Scale", // 右下角缩略图插件 比例尺
          "AMap.OverView", // 地图鹰眼插件
          "AMap.ToolBar", // 地图工具条
          "AMap.PolyEditor", // 编辑 折线多，边形
          "AMap.CircleEditor", // 圆形编辑器插件
          "AMap.Geocoder",
        ],
      })
        .then((AMap) => {
          this.areaMap = new AMap.Map("area", {
            resizeEnable: true,
            zoom: 14, //初始化地图级别
            center: [
              this.form.gpsLongitude || 120.699279,
              this.form.gpsLatitude || 27.993849,
            ], //初始化地图中心点位置
            viewMode: "3D",
          });
          this.areaMap.setDefaultCursor("pointer");
          if (this.areaForm.range && this.areaForm.range.length) {
            this.rangeDraw();
          }
          if (this.areaForm.control && this.areaForm.control.length) {
            this.controlDraw();
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // 地图-放大
    checkAreaEnlarge() {
      this.areaMap.setZoom((this.zoomSize += 1));
    },
    // 地图-缩小
    checkAreaNarrow() {
      if (this.zoomSize > 8) {
        this.areaMap.setZoom((this.zoomSize -= 1));
      }
    },
    beforeUpload(file) {
      if (file.name.indexOf("shp") < 0) {
        this.$message.error("请上传shp文件");
        return false;
      }
    },
    customRequest1(data){
      console.log(data)
      const params = new FormData();
      params.append('file', data.file);
      params.append('fileClassCode','99');//文件分类 20：小程序 10:pc申报  11：pc审核
      params.append('uploaderId',this.$store.state.user.userInfo.userId);
      this.$http.post(fileUploadUrl,params).then((res) => {
        console.log(res)
        if (res.result.file.flag === true) {
          // data.onSuccess(res.result.file,data.file)
          this.fileList1 = [{
            uid: '1',
            name: data.file.name,
            status: 'done',
            showId: res.result.file.showId,
          }]
          const formData = new FormData();
          formData.append('file', data.file);
          this.$http.httpAction(readSHP,formData,'post').then(res =>{
            this.b0119Data = []
            this.$message.info("文件读取成功");
            this.fileList1[0].datas = res.datas
            res.datas.forEach((item) => {
              this.rangeDraw(eval('[' +  item.the_geom + ']'), '#9640ff');
            })
            this.$emit('saveFileList1',this.fileList1)
          }).catch(err =>{
            this.$message.info("文件读取失败");
          })
        }
      }).catch((res) => {
        this.fileList1 = [{
          uid: '-1',
          name: data.file.name,
          status: 'error',
        }]
        this.$message.error("文件上传失败");
      })
    },
    // 文物保护范围上传
    handleRange(info) {
      if(info.fileList.length === 0){//删除
        this.fileList1 = info.fileList;
        this.$emit('saveFileList1',this.fileList1)
      }
    },
    // 建设控制地带范围上传
    handleControl(info) {
      if(info.fileList.length === 0){//删除
        this.fileList2 = info.fileList;
        this.$emit('saveFileList2',this.fileList2)
      }
    },
    customRequest2(data){
      console.log(data)
      const params = new FormData();
      params.append('file', data.file);
      params.append('fileClassCode','99');//文件分类 20：小程序 10:pc申报  11：pc审核
      params.append('uploaderId',this.$store.state.user.userInfo.userId);
      this.$http.post(fileUploadUrl,params).then((res) => {
        console.log(res)
        if (res.result.file.flag === true) {
          // data.onSuccess(res.result.file,data.file)
          this.fileList2 = [{
            uid: '1',
            name: data.file.name,
            status: 'done',
            showId: res.result.file.showId,
          }]
          const formData = new FormData();
          formData.append('file', data.file);
          this.$http.httpAction(readSHP,formData,'post').then(res =>{
            this.b0120Data = []
            this.$message.info("文件读取成功");
            this.fileList2[0].datas = res.datas
            res.datas.forEach((item) => {
              this.rangeDraw(eval('[' +  item.the_geom + ']'), '#ff8940');
            })
            this.$emit('saveFileList2',this.fileList2)
          }).catch(err =>{
            this.$message.info("文件读取失败");
          })
        }
        return file;
      });
    },
    // 文物保护范围图形绘制
    rangeDraw(list, color) {
      list = list.map((item) => {
        return [item[1], item[0]]
      } )
      L.polygon(list, {
        lineJoin: 'dashed',
        color,
        fillColor: color,
        fillOpacity: 0.4,
      }).addTo(this.map);
    },
    addPolygon(data) {
      let polygon = new AMap.Polygon({
        path: data,
        fillColor: "#ccebc5",
        strokeOpacity: 1,
        fillOpacity: 0.5,
        strokeColor: "#2b8cbe",
        strokeWeight: 1,
        strokeStyle: "dashed",
        strokeDasharray: [5, 5],
      });
      polygon.on("mouseover", () => {
        polygon.setOptions({
          fillOpacity: 0.7,
          fillColor: "#7bccc4",
        });
      });
      polygon.on("mouseout", () => {
        polygon.setOptions({
          fillOpacity: 0.5,
          fillColor: "#ccebc5",
        });
      });
      map.add(polygon);
    },
    // 建设控制地带范围上传前钩子函数
    boforeControl(file) {
      // this.handleControl()正常是接口调用后触发的函数，这里是为了能点击上传就显示效果。实际中需要删除
      // this.handleControl();
      let type = file.type;
      if (type.indexOf("shp") < 0) {
        this.$message.error("请上传shp文件");
        return false;
      }
    },
    // 开始编辑
    startEdit() {
      this.rangeEditor ? this.rangeEditor.open() : "";
      this.controlEditor ? this.controlEditor.open() : "";
      if (this.rangeEditor || this.controlEditor) {
        this.isPolygonEdit = true;
      }
    },
    // 结束编辑
    endEdit() {
      this.isPolygonEdit = false;
      if (this.rangeEditor) {
        this.rangeEditor.close();
        const rangeArr = this.rangePolygon.getPath().map((el) => {
          return gcj02towgs84(el.lng, el.lat);
        });
        this.$set(this.areaForm, "range", rangeArr);
      }
      if (this.controlEditor) {
        this.controlEditor.close();
        const controlArr = this.controlPolygon.getPath().map((el) => {
          return gcj02towgs84(el.lng, el.lat);
        });
        this.$set(this.areaForm, "control", controlArr);
      }
    },
    // 设控制地带范围图形绘制
    // controlDraw() {
    //   if (this.controlPolygon) {
    //     this.controlPolygon.setMap(null);
    //   }
    //   AMap.convertFrom(this.areaForm.control, "gps", (status, result) => {
    //     if (status == "complete") {
    //       this.controlPolygon = new AMap.Polygon({
    //         path: result.locations,
    //         strokeColor: "red",
    //         strokeStyle: "dashed",
    //         strokeWeight: 2,
    //         fillColor: "transprent",
    //         zIndex: 80,
    //         bubble: true,
    //       });
    //       this.controlPolygon.setMap(this.areaMap);
    //       // 缩放地图到合适的视野级别
    //       this.areaMap.setFitView();
    //     } else {
    //       this.$message.error("坐标转换失败，请联系管理员！");
    //     }
    //   });
    // },
  },
};
</script>

<style lang="less" scoped>
.map-box {
  position: relative;
  height: 600px;

  #gssp {
    height: 100%;
  }

  #map {
    //width: 1200px;
    height: 100%;
  }

  .scale {
    position: absolute;
    top: 20px;
    left: 20px;
    width: 30px;
    height: 80px;
    display: flex;
    flex-direction: column;

    p {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #dfdfdf;
      background: #fff;
      font-size: 22px;
      cursor: pointer;
      color: #49bbeb;
      &:first-child {
        border-top-left-radius: 3px;
        border-top-right-radius: 3px;
      }

      &:last-child {
        border-top: none;
        border-bottom-left-radius: 3px;
        border-bottom-right-radius: 3px;
      }

      &:hover {
        background: #f2f2f2;
      }
    }
  }
  .eidt {
    position: absolute;
    left: 60px;
    top: 20px;
  }
}

.shp-upload {
  display: flex;
  align-items: center;
  padding: 10px 0;

  > div {
    margin-right: 10px;
  }

  > span {
    padding-left: 10px;
    color: #888;
  }
}
</style>
<style>
.amap-logo,
.amap-copyright {
  display: none !important;
}
</style>
